﻿using Newbe.TestDirector.Notification.Web.Domain;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using RazorEngine.Text;
using System.IO;

namespace Newbe.TestDirector.Notification.Web.Jobs
{
    internal class QqMailNotificator : INotificator
    {
        private static readonly IRazorEngineService RazorEngineService;
        static QqMailNotificator()
        {
            var config = new TemplateServiceConfiguration
            {
                Debug = true,
                EncodedStringFactory = new RawStringFactory()
            };
            RazorEngineService = RazorEngine.Templating.RazorEngineService.Create(config);
        }
        private readonly SystemOptions _systemOptions;
        private readonly IDomainEventLogService _domainEventLogService;

        public QqMailNotificator(SystemOptions systemOptions, IDomainEventLogService domainEventLogService)
        {
            _systemOptions = systemOptions;
            _domainEventLogService = domainEventLogService;
        }

        public void Notificat(NotificatContext notificatContext)
        {
            var mailerSenderBookCollection = notificatContext.MailerSenderBookCollection;
            IMailer mailer = new QqMailer(_systemOptions.MailerOptions);
            foreach (var bookItem in mailerSenderBookCollection)
            {
                var result =
                    RazorEngineService.RunCompile(
                        File.ReadAllText(_systemOptions.MailBodyTemplateFilePath), "templateKey", typeof(MailerSenderBookItem),
                        bookItem);
                var mailbody = result;
                mailer.Send(new MailerSendContext
                {
                    Body = mailbody,
                    Title = "不动产登记云平台需求管理TD变更提醒",
                    ToAddress = bookItem.MailerInfo.MailAddress
                });
                _domainEventLogService.AddDoaminEventLog("发送邮件成功",
                    $"向{bookItem.MailerInfo.MailAddress}发送邮件成功，邮件内容为:{mailbody}");
            }
        }
    }
}
